package socket

import (
	"github.com/gorilla/websocket"
	"log"
	"time"
)

// 注册注销
func register() {
	for {
		select {
		case conn := <-RegisterChan: // 新注册，新连接
			// 加入连接,进行管理
			accountBind(conn)

			// 回复消息
			content := CreateReplyMsg(MessageTypeRegister, ServiceMessageContent{})
			_ = conn.Socket.WriteMessage(websocket.TextMessage, content)

		case conn := <-unregisterChan: // 注销，或者没有心跳
			// 关闭连接
			_ = conn.Socket.Close()

			// 删除Client
			unAccountBind(conn)
		}
	}
}

// 绑定账号
func accountBind(c *Client) {
	Manager.mu.Lock()
	defer Manager.mu.Unlock()

	// 加入到连接
	Manager.Clients[c.ID] = c

	// 加入到绑定
	if _, ok := Manager.Accounts[c.CustomerId]; ok { // 该账号已经有绑定，就追加一个绑定
		Manager.Accounts[c.CustomerId] = append(Manager.Accounts[c.CustomerId], c.ID)
	} else { // 没有就新增一个账号的绑定切片
		Manager.Accounts[c.CustomerId] = []string{c.ID}
	}
}

// 解绑账号
func unAccountBind(c *Client) {
	Manager.mu.Lock()
	defer Manager.mu.Unlock()

	// 取消连接
	delete(Manager.Clients, c.ID)

	// 取消绑定
	if len(Manager.Accounts[c.CustomerId]) > 0 {
		for k, clientId := range Manager.Accounts[c.CustomerId] {
			if clientId == c.ID { // 找到绑定客户端Id
				Manager.Accounts[c.CustomerId] = append(Manager.Accounts[c.CustomerId][:k], Manager.Accounts[c.CustomerId][k+1:]...)
			}
		}
	}
}

// 维持心跳
func heartbeat() {
	for {
		// 获取所有的Clients
		Manager.mu.Lock()
		clients := make([]*Client, len(Manager.Clients))
		for _, c := range Manager.Clients {
			clients = append(clients, c)
		}
		Manager.mu.Unlock()

		for _, c := range clients {
			if time.Now().Unix()-c.HeartbeatTime > HeartbeatTime {
				unAccountBind(c)
			}
		}

		time.Sleep(time.Second * HeartbeatCheckTime)
	}
}

// 管理连接
func Start() {
	// 检查心跳
	go func() {
		defer func() {
			if r := recover(); r != nil {
				log.Println(r)
			}
		}()
		heartbeat()
	}()

	// 注册注销
	go func() {
		defer func() {
			if r := recover(); r != nil {
				log.Println(r)
			}
		}()
		register()
	}()
}
